#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: chenchao 2018/4/3

#爬壁纸网站 信息
#http://www.netbian.com/index_2.htm
import json
import random
import datetime
import threading

import os
import re
import requests
import time

import sys

import thread
from bs4 import BeautifulSoup
import PyQt4
import chardet
from PyQt4 import QtGui, QtCore
from ui_widget import *

# qt的QString转str，转utf-8
def qstring_to_str(string):
    return string.toLocal8Bit().data().decode('gb2312').encode("utf-8")

# utf-8格式的str转QString
def str_to_qstring(str):
    return QtCore.QString.fromUtf8(str)

def get_one_page(url, data=None, proxy=None, headers=None):
    try:
        s = requests.session()
        s.keep_alive = False
        s.adapters.DEFAULT_RETRIES = 5
        req = s.get(url, timeout=20, headers=headers, data=data, proxies=proxy)

        if req.status_code == 200:
            req.encoding='utf-8'
            return req.text
        return None
    except:
        return None

def get_one_page_content(url, data=None, proxy=None, headers=None):
    try:
        s = requests.session()
        s.keep_alive = False
        s.adapters.DEFAULT_RETRIES = 5
        req = s.get(url, timeout=5, headers=headers, data=data, proxies=proxy)

        if req.status_code == 200:
            req.encoding='utf-8'
            return req.content
        return None
    except:
        return None

def post_one_page(url, data=None, headers=None):
    try:
        s = requests.session()
        s.keep_alive = False
        s.adapters.DEFAULT_RETRIES = 5
        req = s.post(url, timeout=5, headers=headers, data=data)

        if req.status_code == 200:
            req.encoding = 'utf-8'
            return req.text
        return None
    except:
        return None

#flag[0:缩略图, 1:原图]
def downImg(url, flag=0):

    content = get_one_page_content(url, headers)
    name = url.split('/')[-1]

    if flag == 0:
        if not os.path.exists('cache'):
            os.makedirs('cache')
        if not os.path.exists('cache/%s' % (name)):
            with open('cache/%s' % (name), 'wb') as f:
                f.write(content)
    else:
        if not os.path.exists('data'):
            os.makedirs('data')
        if not os.path.exists('data/%s' % (name)):
            with open('data/%s' % (name), 'wb') as f:
                f.write(content)

    # w.addImg(name)

def handle_one_page(html):
    lendar = datetime.datetime.now().date()

    year = lendar.year
    month = lendar.month
    day = lendar.day

    bs4 = BeautifulSoup(html, 'lxml')

    section_list = bs4.findAll('div', {'class': 'list'})
    if len(section_list) > 0:
        try:
            section = section_list[0].ul

            pattern = re.compile(r'src="(.*?)"', re.S)
            imgList = re.findall(pattern, str(section))

            for img in imgList:
                # print('img=', img)
                downImg(img, 0)
        except:
            section = ''

    # print(section)

def main():
    global currentPage
    url = 'http://www.netbian.com/index_%s.htm' % str(currentPage)
    html = get_one_page(url, headers=headers)
    currentPage += 1

    print(url)

    if html:
        handle_one_page(html)
    else:
        print('html is none', url)

    # threadTimer = threading.Timer(60.0, main)
    # threadTimer.start()

def handleTimer():
    # threadTimer.start()
    main()

def write_log(log):
    with open('log.txt', 'a+') as f:
        f.write(log+'\n')

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
    'Cookie': '__cfduid=d252e3981db5eb8f693b010f5dfd5ddd01524029979; _ga=GA1.2.1939131297.1524029968; _gid=GA1.2.1452726850.1524029968; wallhaven_session=eyJpdiI6Ik1NU0F1S1hBZGIzUWxQd083b05lMGdnKzBqbFwvaEZnNWx6aXBWczlydE5nPSIsInZhbHVlIjoiOG4rMGlVcHNsQ3ZIY3FDOXRncjR5VnF1RVwvak9WSmR4SzhKTms0TzdCQTFrXC9TZTFEQXBYbmlybnRHd2dyRDdvVmZUck9MSnFmdkprNmxONmVzUXpjZz09IiwibWFjIjoiMGZhOTYyYmViOGNlOGZiMjkyOTRkMWIxOThjYmE5MTFiMWJmODM4NTdjMjc0MjNiZGMzNWVkYmQ1NzRmNjI0OCJ9'
}

class MyThread(QtCore.QThread):

    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)

    def run(self):
        handleTimer()


class Widget(QtGui.QWidget):

    #定义槽
    @QtCore.pyqtSlot('PyQt_PyObject')
    def playImg(self):

        if self._currentIndex < len(self._names):
            path = self._names[self._currentIndex]
            pix = QtGui.QPixmap(path)
            # if pix.isNull():
            #     if pix.isNull():
            #         write_log(path)
            #     path = path.replace('\\', '/')
            #     pix = QtGui.QPixmap(path)
            #
            # if pix.isNull():
            #     if pix.isNull():
            #         write_log(path)
            #     path = path.replace('/', '\\\\')
            #     pix = QtGui.QPixmap(path)

            self.ui.label.setPixmap(pix)
            self._currentIndex += 1

            if pix.isNull():
                write_log(path)
        else:
            self._currentIndex = 0

        if len(self._names) == 0:
            self._thread.start()

    def addImg(self, name):
        # print('ad==',name)
        if not name in self._names:
            self._names.append(name)
            # write_log(name)

        if len(self._names) == 1:
            self.playImg()
            self._timer.start()

    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.resize(300, 188)
        self.setWindowTitle(u'壁纸欣赏')
        self.ui.label.setText(u'初始化...')

        #每10s滚动图片
        self._currentIndex = 0
        self._names = []
        self._timer = QtCore.QTimer()
        self._timer.setInterval(1000 * 10)
        self._timer.timeout.connect(self.playImg)
        self._timer.start()

        self._thread = MyThread(self)
        # self._thread.start()

        self._watcher = QtCore.QFileSystemWatcher()
        global currentPath

        if not os.path.exists('cache'):
            os.makedirs('cache')
        self._watcher.addPath(os.path.join(currentPath, 'cache'))
        self._watcher.directoryChanged.connect(self.handleWatcher)

        self.handleWatcher(str_to_qstring(os.path.join(currentPath, 'cache')))

        # 每20分钟爬新图片
        self.timerThread = QtCore.QTimer()
        self.timerThread.setInterval(1000 * 60 * 20)
        self.timerThread.timeout.connect(self._thread.start)
        self.timerThread.start()

        # write_log(os.path.join(currentPath, 'cache'))

    def resizeEvent(self, event):
        try:
            pix = self.ui.label.pixmap()
            pix.scaled(self.ui.label.size(), QtCore.Qt.KeepAspectRatio)
            self.ui.label.setScaledContents(True)
            self.ui.label.setPixmap(pix)
        except:
            pass


    def closeEvent(self, event):
        event.accept()

    #监视文件夹更新
    def handleWatcher(self, path):
        for (dirpath, dirnames, filenames) in os.walk(qstring_to_str(path)):
            for file in filenames:
                p = (os.path.join(currentPath, 'cache', file))
                self.addImg(p)


if __name__ == '__main__':
    # threadTimer = threading.Timer(60.0, main)
    updateTime = ''
    currentPage = 2
    currentPath, exeName = os.path.split(os.path.abspath(sys.argv[0]))

    # write_log(currentPath)

    app = QtGui.QApplication(sys.argv)

    w = Widget()
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap('favicon.ico'), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    w.setWindowIcon(icon)

    w.show()

    sys.exit(app.exec_())
